package com.me.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.me.app.R;
import com.me.data.DBItem;
import com.me.util.AppConstant;

public class DBListAdapter extends ArrayAdapter<DBItem> {
	
	public DBListAdapter(Context context, List<DBItem> itemList) {
		super(context, R.layout.db_item, itemList);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		DBItemView dbItemView;

		if (convertView == null) {
			// inflate the list view item layout
			LayoutInflater inflater = LayoutInflater.from(getContext());
			convertView = inflater.inflate(R.layout.db_item, parent, false);

			// initialize the item view
			dbItemView = new DBItemView();
			
			dbItemView.tvPrefix = (TextView) convertView
					.findViewById(R.id.tvPrefix);
			dbItemView.tvName = (TextView) convertView
					.findViewById(R.id.tvName);
			dbItemView.tvCount = (TextView) convertView
					.findViewById(R.id.tvCount);			
			convertView.setTag(dbItemView);

		} else {
			// recycle the already inflated view
			dbItemView = (DBItemView) convertView.getTag();
		}

		final DBItem dbItem = (DBItem) getItem(position);

		// set prefix
		dbItemView.tvPrefix.setText(dbItem.getPrefix());

		if (position == 0) {
			dbItemView.tvPrefix.setVisibility(View.VISIBLE);
		} else {
			dbItemView.tvPrefix.setVisibility(View.GONE);
			DBItem prevItem = (DBItem) getItem(position - 1);
			if (!prevItem.getPrefix().equals(dbItem.getPrefix()))
				dbItemView.tvPrefix.setVisibility(View.VISIBLE);
		}

		// set name
		String name = dbItem.getName();
		if (name != null && name.length() > 0) {
			dbItemView.tvName.setText(name);
		} else {
			dbItemView.tvName.setText(AppConstant.EVENT_ITEM_NO_TITLE);
		}
	
		// set count
		int count = dbItem.getCount();
			dbItemView.tvCount.setText(String.valueOf(count));
				
	
		return convertView;
	}

	public static class DBItemView {
		TextView tvPrefix;
		TextView tvName;
		TextView tvCount;
	}

}
